"""
配置管理API v2 - 学校配置和系统配置管理
"""

import logging
from flask import Blueprint, request

from ..middleware import ResponseFormatter
from ..services.integrations import ConfigService
from ..services.core import PatternMatchingService


logger = logging.getLogger(__name__)
config_bp = Blueprint('config_v2', __name__, url_prefix='/api/v2/config')


@config_bp.route('/schools', methods=['GET'])
def list_school_configs():
    """列出所有学校配置"""
    try:
        config_service = ConfigService()
        
        # 获取所有配置文件
        result = config_service.list_available_configs()
        
        if result.success:
            return ResponseFormatter.success(
                message="学校配置列表获取成功",
                data=result.details
            )
        else:
            return ResponseFormatter.error(
                message=result.message,
                error_code="LIST_CONFIGS_ERROR"
            )
            
    except Exception as e:
        logger.error(f"列出学校配置失败: {e}")
        return ResponseFormatter.error(
            message=f"列出学校配置失败: {str(e)}",
            error_code="LIST_SCHOOL_CONFIGS_ERROR"
        )


@config_bp.route('/schools/<school_name>', methods=['GET'])
def get_school_config(school_name: str):
    """获取指定学校的配置"""
    try:
        config_service = ConfigService()
        
        # 获取学校配置
        result = config_service.get_school_config(school_name)
        
        if result.success:
            return ResponseFormatter.success(
                message=f"学校配置获取成功: {school_name}",
                data=result.details
            )
        else:
            return ResponseFormatter.error(
                message=result.message,
                error_code="GET_SCHOOL_CONFIG_ERROR"
            )
            
    except Exception as e:
        logger.error(f"获取学校配置失败: {e}")
        return ResponseFormatter.error(
            message=f"获取学校配置失败: {str(e)}",
            error_code="GET_SCHOOL_CONFIG_ERROR"
        )


@config_bp.route('/schools/<school_name>', methods=['POST'])
def save_school_config(school_name: str):
    """保存学校配置"""
    try:
        data = request.get_json()
        
        if not data:
            return ResponseFormatter.error(
                message="请求数据为空",
                error_code="EMPTY_REQUEST_DATA"
            )
        
        config_service = ConfigService()
        
        # 验证配置格式
        validation_result = config_service.validate_config(data)
        if not validation_result.success:
            return ResponseFormatter.error(
                message=f"配置格式错误: {validation_result.message}",
                error_code="CONFIG_VALIDATION_ERROR"
            )
        
        # 保存配置
        result = config_service.save_school_config(school_name, data)
        
        if result.success:
            return ResponseFormatter.success(
                message=f"学校配置保存成功: {school_name}",
                data=result.details
            )
        else:
            return ResponseFormatter.error(
                message=result.message,
                error_code="SAVE_SCHOOL_CONFIG_ERROR"
            )
            
    except Exception as e:
        logger.error(f"保存学校配置失败: {e}")
        return ResponseFormatter.error(
            message=f"保存学校配置失败: {str(e)}",
            error_code="SAVE_SCHOOL_CONFIG_ERROR"
        )


@config_bp.route('/current-school', methods=['GET'])
def get_current_school():
    """获取当前学校信息"""
    try:
        config_service = ConfigService()
        
        current_school = config_service.get_current_school_info()
        
        if current_school:
            return ResponseFormatter.success(
                message="当前学校信息获取成功",
                data=current_school
            )
        else:
            return ResponseFormatter.success(
                message="尚未设置当前学校",
                data=None
            )
            
    except Exception as e:
        logger.error(f"获取当前学校信息失败: {e}")
        return ResponseFormatter.error(
            message=f"获取当前学校信息失败: {str(e)}",
            error_code="GET_CURRENT_SCHOOL_ERROR"
        )


@config_bp.route('/current-school', methods=['POST'])
def set_current_school():
    """设置当前学校信息"""
    try:
        data = request.get_json()
        
        school_name = data.get('school_name')
        school_id = data.get('school_id', '')
        base_image = data.get('base_image', 'mobox-python-hardware:latest')
        
        if not school_name:
            return ResponseFormatter.error(
                message="缺少学校名称",
                error_code="MISSING_SCHOOL_NAME"
            )
        
        config_service = ConfigService()
        
        # 设置当前学校信息
        result = config_service.set_current_school_info(school_name, school_id, base_image)
        
        if result.success:
            return ResponseFormatter.success(
                message=f"当前学校信息设置成功: {school_name}",
                data=result.details
            )
        else:
            return ResponseFormatter.error(
                message=result.message,
                error_code="SET_CURRENT_SCHOOL_ERROR"
            )
            
    except Exception as e:
        logger.error(f"设置当前学校信息失败: {e}")
        return ResponseFormatter.error(
            message=f"设置当前学校信息失败: {str(e)}",
            error_code="SET_CURRENT_SCHOOL_ERROR"
        )


@config_bp.route('/pattern-matching', methods=['GET'])
def get_pattern_matching_config():
    """获取模式匹配配置"""
    try:
        pattern_service = PatternMatchingService()
        
        # 读取模式匹配配置文件
        import json
        config_file = '/home/mobox/mobox_dashboard/config/pattern_matching.json'
        
        with open(config_file, 'r', encoding='utf-8') as f:
            pattern_config = json.load(f)
        
        return ResponseFormatter.success(
            message="模式匹配配置获取成功",
            data=pattern_config
        )
        
    except Exception as e:
        logger.error(f"获取模式匹配配置失败: {e}")
        return ResponseFormatter.error(
            message=f"获取模式匹配配置失败: {str(e)}",
            error_code="GET_PATTERN_CONFIG_ERROR"
        )


@config_bp.route('/pattern-matching/test', methods=['POST'])
def test_pattern_matching():
    """测试模式匹配"""
    try:
        data = request.get_json()
        image_name = data.get('image_name')
        
        if not image_name:
            return ResponseFormatter.error(
                message="缺少镜像名称",
                error_code="MISSING_IMAGE_NAME"
            )
        
        pattern_service = PatternMatchingService()
        
        # 测试模式匹配
        pattern_info = pattern_service.get_pattern_info(image_name)
        full_url = pattern_service.build_full_image_url(image_name)
        compose_file = pattern_service.select_compose_file(image_name)
        
        test_result = {
            "image_name": image_name,
            "pattern_info": pattern_info,
            "full_image_url": full_url,
            "compose_file": compose_file,
            "compose_exists": pattern_service.validate_compose_file(compose_file).success
        }
        
        return ResponseFormatter.success(
            message="模式匹配测试完成",
            data=test_result
        )
        
    except Exception as e:
        logger.error(f"模式匹配测试失败: {e}")
        return ResponseFormatter.error(
            message=f"模式匹配测试失败: {str(e)}",
            error_code="PATTERN_MATCHING_TEST_ERROR"
        )